var express = require('express');
var router = express.Router();
var User = require('../models/users.js');
var errFn = require('../util/err.js');
require('../util/util.js');

// 登录接口
router.post('/login', function(req, res, next) {
  var param = {
  	userName: req.body.userName,
  	userPwd: req.body.userPwd
  }
  User.findOne(param, function (err, doc) {
  	if (err) {
  		res.json({
  			status: 1,
  			msg: err.message
  		})
  	} else {
  		if (doc) {
  			res.cookie("userId", doc.userId,{
  				path: '/',
  				maxAge: 1000*60*60
  			});
  			res.cookie("userName", doc.userName,{
  				path: '/',
  				maxAge: 1000*60*60
  			});
  			// req.session.user = doc;  需要安装 express-session
  			res.json({
  				status: 0,
  				msg: '',
  				result: {
  					userName: doc.userName
  				}
  			})
  		} else {
  			res.json({
  				status: 1,
  				msg: '用户名或密码不正确'
  			})
  		}
  	}
  })
});
// 登出接口
router.post('/loginOut', function(req, res, next) {
	res.cookie("userId", "", {
		path: '/',
		maxAge: -1
	});
	res.json({
		status: 0,
		msg: '',
		result: ''
	})
})
// 校验
router.get("/checkLogin", function (req,res,next) {
	if (req.cookies.userId) {
		res.json({
			status: 0,
			msg: '',
			result: {
				userName: req.cookies.userName
			}
		})
	} else {
		res.json({
			status: 1,
			msg: '未登录',
			result: {
				userName: ''
			}
		})
	}
})
// 获取购物车列表
router.get("/cartList", function (req, res,next) {
	var userId = parseInt(req.cookies.userId);
	User.findOne({userId: userId}, function (err, doc) {
		if (err) {
			res.json({
				status: 1,
				msg: err.message,
				result: ''
			})
		} else {
			if (doc) {
				res.json({
					status: 0,
					msg: '',
					result: doc.cartList
				})
			}
		}
	})
})
// 获取商品数量
// 获取购物车列表
router.get("/getCartCount", function (req, res,next) {
	if (req.cookies && req.cookies.userId) {
		var userId = parseInt(req.cookies.userId);
		User.findOne({userId: userId}, function (err, doc) {
			if (err) {
				res.json({
					status: 1,
					msg: err.message,
					result: ''
				})
			} else {
				if (doc) {
					var cartList = doc.cartList
					let cartCount = 0
					cartList.forEach((item) => {
						cartCount += parseInt(item.productNum)
					})
					res.json({
						status: 0,
						msg: '',
						result: cartCount
					})
				}
			}
		})
	}
})
// 购物车删除
router.post("/cart/del", function (req, res,next) {
	var userId = parseInt(req.cookies.userId);
	var productId = req.body.productId;
	User.update({
		userId: userId
	}, {
		$pull: {
			'cartList':{
				'productId': productId
			}
		}
	}, function (err, doc) {
		errFn(err, res, function () {
			res.json({
				status: 0,
				msg: '',
				result: 'suc'
			})
		})
	})
})
// 购物车修改
router.post("/cartEdit", function (req, res,next) {
	var userId = parseInt(req.cookies.userId);
	var productId = req.body.productId;
	var productNum = req.body.productNum;
	var checked = req.body.checked;
	User.update({
		userId: userId,
		'cartList.productId': productId
	}, {
		// 这里是修改子文档
		'cartList.$.productNum': productNum,
		'cartList.$.checked': checked
	}, function (err, doc) {
		errFn(err, res, function () {
			res.json({
				status: 0,
				msg: '',
				result: 'suc'
			})
		})
	})
})
router.post("/editCheckAll", function (req, res,next) {
	var userId = parseInt(req.cookies.userId);
	var checkAll = req.body.checkAll ? "1" : "0"
	User.findOne({
		userId: userId
	}, function (err, doc) {
		errFn(err, res, function () {
			doc.cartList.forEach((item) => {
				item.checked = checkAll
			})
			doc.save(function (err1, doc1) {
				errFn(err, res, function () {
					res.json({
						status: 0,
						msg: '',
						result: 'suc'
					})
				})
			})
		})
	})
})
// 查询用户地址接口
router.get("/addressList", function (req, res,next) {
	var userId = parseInt(req.cookies.userId);
	User.findOne({userId: userId}, function (err, doc) {
		errFn(err, res, function () {
			if (doc) {
				res.json({
					status: 0,
					msg: '',
					result: doc.addressList
				})
			}
		})
	})
})
// 修改默认地址
router.post("/setDefault", function (req, res,next) {
	var userId = parseInt(req.cookies.userId);
	var addressId = req.body.addressId;
	if (!addressId) {
		res.json({
			status: 1,
			msg: '地址id不能为空',
			result: ''
		})
	}
	User.findOne({
		userId: userId
	}, function (err, doc) {
		errFn(err, res, function () {
			var addressList = doc.addressList;
			addressList.forEach((item) => {
				if (item.addressId == addressId) {
					item.isDefault = true
				} else {
					item.isDefault = false
				}
			})
			doc.save(function (err1, doc1) {
				errFn(err, res, function () {
					res.json({
						status: 0,
						msg: '',
						result: ''
					})
				})
			})
		})
	})
})
// 删除地址
router.post("/address/del", function (req, res,next) {
	var userId = parseInt(req.cookies.userId);
	var addressId = req.body.addressId;
	if (!addressId) {
		res.json({
			status: 1,
			msg: '地址id不能为空',
			result: 'suc'
		})
	}
	User.update({
		userId: userId
	}, {
		$pull: {
			'addressList':{
				'addressId': addressId
			}
		}
	}, function (err, doc) {
		errFn(err, res, function () {
			res.json({
				status: 0,
				msg: '',
				result: 'suc'
			})
		})
	})
})
// 新增地址
router.post("/address/add", function (req, res,next) {
	var userId = parseInt(req.cookies.userId);
	var userName = req.cookies.userName;
	var streetName = req.body.streetName;
	var postCode = req.body.postCode;
	var tel = req.body.tel;
	if (!streetName) {
		res.json({
			status: 1,
			msg: 'streetName不能为空',
			result: 'suc'
		})
	}
	if (!postCode) {
		res.json({
			status: 1,
			msg: 'postCode不能为空',
			result: 'suc'
		})
	}
	if (!tel) {
		res.json({
			status: 1,
			msg: 'tel不能为空',
			result: 'suc'
		})
	}
	User.findOne({
		userId: userId
	}, function (err, doc){
		errFn(err, res, function () {
			var addressId = 0
			if (doc.addressList.length > 0) {
				addressId = 1
			} else {
				addressId = doc.addressList[doc.addressList.length - 1].addressId
			}
			var newAddressId = (parseInt(addressId) + 1) + ''
			User.update({
				userId: userId
			}, {
				$push: {
					'addressList':{
						'addressId': newAddressId,
						'userName': userName,
						'streetName': streetName,
						'postCode': postCode,
						'tel': tel,
						'isDefault': false
					}
				}
			}, function (err, doc) {
				errFn(err, res, function () {
					res.json({
						status: 0,
						msg: '',
						result: 'suc'
					})
				})
			})
		})
	})
})
// 生成订单
router.post("/payMent", function (req, res,next) {
	var userId = parseInt(req.cookies.userId);
	var orderTotal = req.body.orderTotal;
	var addressId = req.body.addressId;
	User.findOne({
		userId: userId
	}, function (err, doc){
		errFn(err, res, function () {
			var address = ''
			var goodsList = []
			// 获取用户的地址信息
			doc.addressList.forEach((item) => {
				if (addressId == item.addressId) {
					address = item
				}
			})
			// 获取用户购物车的购买商品
			doc.cartList.filter((item) => {
				if (item.checked == 1) {
					goodsList.push(item)
				}
			})

			var platform = '622'
			var r1 = Math.floor(Math.random() * 10)
			var r2 = Math.floor(Math.random() * 10)
			var sysDate = new Date().Format('yyyyMMddhhmmss')
			var createDate = new Date().Format('yyyy-MM-dd hh:mm:ss')
			var orderId = platform + r1 + sysDate + r2

			var order = {
				orderId: orderId,
				orderTotal: orderTotal,
				addressInfo: address,
				goodsList: goodsList,
				orderStatus: 1,
				createDate: createDate
			}
			doc.orderList.push(order);
			doc.save(function (err1, doc1) {
				errFn(err1, res, function () {
					res.json({
						status: 0,
						msg: '',
						result: {
							orderId: order.orderId,
							orderTotal: order.orderTotal
						}
					})
				})
			})
		})
	})
})

module.exports = router;
